using System;
using NHibernate;
using NHibernate.Criterion;

namespace TelerikMvcGridCustomBindingHelper.NHibernate.Aggregates
{
    public static class AggregatesHelper
    {
        private static IFutureValue<object> GetFutureValue(IQueryOver queryOver, IProjection aggregateProjection)
        {
            var projection = CriteriaTransformer.Clone(queryOver.RootCriteria).SetProjection(aggregateProjection);
            return projection.FutureValue<object>();
        }

        public static IFutureValue<object> Sum<TEntity>(string propertyName, IQueryOver<TEntity, TEntity> queryOver)
        {
            var aggregateProjection = global::NHibernate.Criterion.Projections.Sum(propertyName);
            return GetFutureValue(queryOver, aggregateProjection);
        }

        public static IFutureValue<object> Count<TEntity>(string propertyName, IQueryOver<TEntity, TEntity> queryOver)
        {
            var aggregateProjection = new BetterCountProjection(propertyName);
            return GetFutureValue(queryOver, aggregateProjection);
        }

        public static IFutureValue<object> Avg<TEntity>(string propertyName, IQueryOver<TEntity, TEntity> queryOver)
        {
            var aggregateProjection = new BetterAvgProjection(propertyName);
            return GetFutureValue(queryOver, aggregateProjection);
        }

        public static IFutureValue<object> Min<TEntity>(String propertyName, IQueryOver<TEntity, TEntity> queryOver)
        {
            var aggregateProjection = global::NHibernate.Criterion.Projections.Min(propertyName);
            return GetFutureValue(queryOver, aggregateProjection);
        }

        public static IFutureValue<object> Max<TEntity>(String propertyName, IQueryOver<TEntity, TEntity> queryOver)
        {
            var aggregateProjection = global::NHibernate.Criterion.Projections.Max(propertyName);
            return GetFutureValue(queryOver, aggregateProjection);
        }
    }
}